package org.example.greenhouse.service.impl;

import org.example.greenhouse.dao.DeviceDao;
import org.example.greenhouse.dao.GreenHouseDao;
import org.example.greenhouse.entity.GreenHouse;
import org.example.greenhouse.result.Result;
import org.example.greenhouse.service.GreenHouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class GreenHouseServiceImpl implements GreenHouseService {
    @Autowired
    private GreenHouseDao greenHouseDao;

    @Autowired
    private DeviceDao deviceDao;

    @Override
    public Result addGreenHouse(GreenHouse greenHouse) {
        try {
            GreenHouse savedGreenHouse = greenHouseDao.save(greenHouse);
            return Result.success(savedGreenHouse, "大棚添加成功");
        } catch (Exception e) {
            return Result.error("大棚添加失败: " + e.getMessage());
        }
    }

    @Override
    public Result getGreenHouseById(Long houseId) {
        Optional<GreenHouse> greenHouseOptional = greenHouseDao.findById(houseId);
        if (greenHouseOptional.isPresent()) {
            GreenHouse greenHouse = greenHouseOptional.get();
            // 查询设备数量并设置到 greenHouse 对象中
            int deviceCount = deviceDao.countByGreenHouseId(houseId);
            greenHouse.setDeviceCount(deviceCount);
            return Result.success(greenHouse, "大棚信息获取成功");
        } else {
            return Result.error("大棚不存在");
        }
    }

    @Override
    public Result getAllGreenHouses() {
        try {
            List<GreenHouse> greenHouses = greenHouseDao.findAll(); // 获取所有大棚数据
            return Result.success(greenHouses, "所有大棚数据获取成功");
        } catch (Exception e) {
            return Result.error("获取所有大棚数据失败: " + e.getMessage());
        }
    }
}
